package com.cxg.fairy.ec.sign;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TextInputEditText;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.AppCompatTextView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.IError;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.widget.CountTimer.CountTimer;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.rengwuxian.materialedittext.MaterialEditText;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by CFairy on 2017/11/22
 */

public class SignUpByNoDelegate extends LatteDelegate {

    private CountTimer countTimer;

    private static String mTel;

    private static String mCode;

    @BindView(R2.id.met_reg_checkcode)
    MaterialEditText textCheckCode = null;

    @BindView(R2.id.met_reg_psw)
    TextInputEditText textRegPsw = null;

    @BindView(R2.id.acb_reg_btn)
    AppCompatButton btnReg = null;

    @BindView(R2.id.act_reg_get_phone_code)
    AppCompatTextView tvCode = null;

    @BindView(R2.id.atv_default_text)
    AppCompatTextView tvDefaultText = null;

    @BindView(R2.id.atv_reg_tel)
    AppCompatTextView tvRegTel = null;

    @OnClick(R2.id.act_reg_get_phone_code)
    void onClickRequestCode() {
        Toasty.info(getContext(), "重新请求验证码！mTel="+mTel).show();
        RestClient.builder()
                .url("getCode")
                .params("phoneNum",mTel)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = JSON.parseObject(response).getInteger("code");
                        String msg = JSON.parseObject(response).getString("message");
                        if (code == 1) {
                        final JSONObject obj = JSON.parseObject(response).getJSONObject("data");
                        String verifyCode = obj.getString("verifyCode");
                        mCode = verifyCode;
                        tvDefaultText.setText(String.format(getResources().getString(R.string.sign_reg_code_again_tips)));
                        countTimer = new CountTimer(60000, 1000,getContext(),tvCode);
                        countTimer.start();
                        } else {
                            Toasty.error(getContext(), msg).show();
                        }
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        Toasty.error(getContext(),"验证码请求失败!").show();
                    }
                })
                .build()
                .post();
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_sign_up_by_no;
    }

    @Override
    public void onBindView(@Nullable final Bundle savedInstanceState, @NonNull View rootView) {

        tvRegTel.setText(mTel);
        countTimer = new CountTimer(60000, 1000,this.getContext(),tvCode);
        countTimer.start();
        textCheckCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkForm()) {
                    setBtnStatus(true);
                }else{
                    setBtnStatus(false);
                }
            }
        });

        textRegPsw.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (checkForm()) {
                    setBtnStatus(true);
                } else {
                    setBtnStatus(false);
                }
            }
        });

    }

    public static SignUpByNoDelegate create(String tel, String code) {
        final Bundle args = new Bundle();
        mTel = tel;
        mCode = code;
        args.putString("tel", tel);
        args.putString("code", code);
        final SignUpByNoDelegate delegate = new SignUpByNoDelegate();
        delegate.setArguments(args);
        return delegate;
    }


    private boolean checkForm() {
        String inputPsw = textRegPsw.getText().toString();
        String inputCode = textCheckCode.getText().toString();
        String code = mCode;
        if (code.equalsIgnoreCase(inputCode) && inputPsw.length() > 6 && inputPsw.length() < 20) {
            return true;
        } else {
            return false;
        }
    }

    private boolean checkCode(String inputCode) {
        if (inputCode.equalsIgnoreCase(mCode)) {
            return true;
        } else {
            return false;
        }
    }

    private void setBtnStatus(boolean status){
        if (status){
            btnReg.setEnabled(true);
            btnReg.setBackgroundColor(Color.parseColor("#018b18"));
        }else{
            btnReg.setEnabled(false);
            btnReg.setBackgroundColor(Color.parseColor("#9c9c9c"));
        }
    }

    private ISignListener mISignListener = null;

    @SuppressWarnings("deprecation")
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof ISignListener) {
            mISignListener = (ISignListener) activity;
        }
    }

    @OnClick(R2.id.acb_reg_btn)
    void onClickSignUp() {
        if (checkCode(textCheckCode.getText().toString())) {
            final String tel = getArguments().getString("tel");
            String psw = textRegPsw.getText().toString();
            RestClient.builder()
                    .url("consumerRegister")
                    .params("username", tel)
                    .params("password",psw)
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            final int code = JSON.parseObject(response).getInteger("code");
                            final String msg = JSON.parseObject(response).getString("message");
                            final JSONObject obj = JSON.parseObject(response).getJSONObject("data");
                            final String uuid = obj.getString("uuid");  //全局存储uuid  存储之前清空
                            if (code == 1) {
                                Toasty.success(getContext(), "注册成功!", Toast.LENGTH_SHORT, true).show();
                                //已经注册并登录成功了
                                AccountManager.setSignState(true);
                                mISignListener.onSignUpSuccess();
                            }else{
                                Toasty.error(getContext(), "注册失败!"+msg, Toast.LENGTH_SHORT, true).show();
                            }
                            getSupportDelegate().start(new SignInDelegate());
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            LatteLogger.e("error.msg", code + "|msg=" + msg);
                        }
                    })
                    .build()
                    .post();
        } else {
            Toasty.error(getContext(), "验证码错误!注册失败!", Toast.LENGTH_LONG, true).show();
        }
    }



}